///
//  httpPostRequest.m
//  ttg
//
//  Created by yons on 16/2/29.
//  Copyright © 2016年 xiaojiang. All rights reserved.
//

#import "httpPostRequest.h"
#define CustomErrorDomain @"test"
typedef enum {
    XDefultFailed = -1000,
    XRegisterFailed,
    XConnectFailed,
    XNotBindedFailed
}CustomErrorFailed;

@implementation httpPostRequest
+(void)getDataByPostAshx:(NSString *)ashx and:(NSDictionary *)parameter withFinishBlock:(GetDataDidFinishBlock)finishBlock{
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager  manager];

    [manger setSecurityPolicy:securityPolicy];
    manger.responseSerializer = [AFJSONResponseSerializer new];
//    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html", nil];
    manger.requestSerializer.timeoutInterval = 10;
    NSString *ip = [NSString stringWithFormat:@"%@%@",IPAddress,ashx];


    [manger POST:ip parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {

        
        NSError *error;
        
//        NSString *responseString = [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding];

        
//        NSString *str = [responseString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];

//        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        

        
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableLeaves error:&error];
        
//        NSLog(@"responseDic%@",responseDic);
//
        finishBlock(responseDic,nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if(finishBlock)
        {
            
            finishBlock(nil,error);
        }
    }];

}


//上传图片
+(void)getDataByPostAshx:(NSString *)ashx and:(NSDictionary *)parameter andImageKeys:(NSArray *)keys andImages:(NSArray *)images withFinishBlock:(GetDataDidFinishBlock)finishBlock{
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    //是否信任无效的服务器或过期的SSL证书 默认是YES
    [securityPolicy setAllowInvalidCertificates:YES];
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager  manager];
    
    [manger setSecurityPolicy:securityPolicy];
    manger.responseSerializer = [AFJSONResponseSerializer new];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html", nil];
    manger.requestSerializer.timeoutInterval = 10;
    NSString *ip = [NSString stringWithFormat:@"%@%@",IPAddress,ashx];
    [manger POST:ip parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (int i = 0; i < keys.count; i++) {
            UIImage *image = (UIImage *)images[i];
            NSData *imageData = UIImagePNGRepresentation(image);
            [formData appendPartWithFileData:imageData name:keys[i] fileName:keys[i] mimeType:@"image/png"];
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error;
        NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:operation.responseData  options:NSJSONReadingMutableLeaves error:&error];
        finishBlock(responseDic,nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if(finishBlock)
        {
            finishBlock(nil,error);
        }
    }];

}

+(void)asiGetDataPost:(NSDictionary *)parameter withFinishBlock:(GetDataDidFinishBlock)finishBlock{
    ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:IPAddress]];
    __weak typeof(ASIFormDataRequest) *req = request;
    for (int i = 0; i<parameter.count; i++) {
        NSString *key = [[parameter allKeys] objectAtIndex:i];
        [request addPostValue:[parameter objectForKey:key] forKey:key];
    }
    [request setCompletionBlock:^{
        //不确定是否需要
        [MBProgressHUD hideHUDForView:nil animated:NO];
        //解析json
        NSData *jsonData = [req.responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
        if(finishBlock)
        {
            finishBlock(dic,nil);
        }
    }];
    
    //回调
    [request setFailedBlock:^{
        NSError *error;
        if(finishBlock)
        {
            finishBlock(nil,error);
        }
    }];
    
    [request startAsynchronous];
}

- (void)downWithUrl:(NSString *)urlString{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];

}
@end
